import {
  login,
  getInfo,
  getDetailInfo
} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: null
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  updateUserInfo: (state, payload) => {
    state.userInfo = payload
  }
}

const actions = {
  // 实现一个actions用来登录
  async login({ commit }, form) {
    // context类似于$store
    // payload是触发action时传递的参数
    try {
      const res = await login({
        mobile: form.username,
        password: form.password
      }

      )
      if (res.code === 10000) {
        // 登录成功,先保存到state里面，再缓存token到本地存储
        commit('SET_TOKEN', res.data)
        setToken(res.data)
        return Promise.resolve(true)
      } else {
        return Promise.reject(false)
      }
    } catch {
      return Promise.reject(false)
    }
  },

  // get user info
  // getInfo({
  //   commit,
  //   state
  // }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const {
  //         data
  //       } = response

  //       if (!data) {
  //         return reject('Verification failed, please Login again.')
  //       }

  //       const {
  //         name,
  //         avatar
  //       } = data

  //       commit('SET_NAME', name)
  //       commit('SET_AVATAR', avatar)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // 获取用户信息
  async getInfo({ commit }) {
    // 调用接口获取用户信息
    const baseInfo = await getInfo()
    const detailInfo = await getDetailInfo(baseInfo.data.userId)
    if (baseInfo.code === 10000) {
      commit('updateUserInfo', {
        ...baseInfo.data,
        ...detailInfo.data
      })
    }
  },
  // user logout
  logout({
    commit
  }) {
    // 删除Token
    commit('SET_TOKEN', '')
    commit('updateUserInfo', null)
    // 删除用户信息

    removeToken()
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }

}

export default {
  // 命名空间，把模块变成局部
  namespaced: true,
  state,
  mutations,
  actions
}
